﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.SiteMap;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:Menu runat=server></{0}:Menu>")]
    public class Menu : SiteMap
    {

        private string getjQueryMenu()
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendLine("var timeout = 500;");
            sb.AppendLine("var closetimer = 0;");
            sb.AppendLine("var ddmenuitem = 0;");
            sb.AppendLine("function menu_open() {");
            sb.AppendLine("menu_canceltimer();");
            sb.AppendLine("menu_close();");
            sb.AppendLine("ddmenuitem = $(this).find('ul').css('visibility', 'visible');}");
            sb.AppendLine("function menu_close() {");
            sb.AppendLine("if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}");
            sb.AppendLine("function menu_timer() {");
            sb.AppendLine("closetimer = window.setTimeout(menu_close, timeout);}");
            sb.AppendLine("function menu_canceltimer() {");
            sb.AppendLine("if(closetimer)");
            sb.AppendLine("{  window.clearTimeout(closetimer);");
            sb.AppendLine("closetimer = null;}}");
            return sb.ToString();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(this.CssClass)) { this.CssClass = "DropDownMenu"; }

            base.Render(writer);
            writer.AddAttribute("language", "javascript");
            writer.AddAttribute("type", "text/javascript");

            writer.RenderBeginTag(HtmlTextWriterTag.Script);

            writer.Write(getjQueryMenu());

            writer.Write("$(document).ready(function() {");
            writer.Write("$('#" + this.ClientID + " > li').bind('mouseover', menu_open);");
            writer.Write("$('#" + this.ClientID + " > li').bind('mouseout',  menu_timer);");
            writer.Write("});");
            writer.Write("document.onclick = menu_close;");
            writer.RenderEndTag();
        }
    }

}

